﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using log4net;

namespace StockAnalyst2
{
	public partial class App : Application
	{
		#region Attributes

		private ILog _log;

		#endregion

		#region Event Handlers

		private void Application_Startup(object sender, StartupEventArgs e)
		{
			_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
			_log.Info("Application starting");

			if (StockAnalyst2.Properties.Settings.Default.ForceSoftRendering)
			{
				RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;				
			}

			Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
			Application.Current.Exit += Current_Exit;
			AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

			System.Threading.Thread.CurrentThread.Name = "Stock Analyst";
			System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");

			using (MainWindowVM mainWindowVM = new MainWindowVM()) // Datacontext has to be created before the main window, otherwise weird things happen when the options dialog is shown for the first time (like columns having wrong autosize)
			{
				using (MainWindow mainWindow = new MainWindow())
				{
					mainWindow.DataContext = mainWindowVM;
					mainWindowVM.Initialize();
					mainWindow.ShowDialog();
				}
			}
		}

		private void Current_Exit(object sender, ExitEventArgs e)
		{
			_log.Info("Application ending");
		}

		private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			_log.Fatal("Unhandled exception detected. The application is terminating: " + e.IsTerminating, (Exception)e.ExceptionObject);
		}

		#endregion
	}
}
